const UploadOss = require('./upload-oss');
const path = require('path');
const fs = require('fs-extra');
const program = require('commander').program;
const config = loadConfig(__dirname, '../upload-oss.online.json'); // 默认线上配置项
const forbiddenUploadTo = ['dist', 'output', 'test', 'target', 'src']; // 禁止上传目录
const cwd = process.cwd(); // 命令执行所在目录

process.on('uncaughtException',function(err){
  const nodeVer = process.version.match(/(\d+)?\./)[1];
  if (nodeVer < 10) {
    console.error(' === upload-oss所需最低node版本 === ', '10.0.0');
    console.error(' === 当前node版本 === ', process.version);
  }
  console.error('____执行报错信息: ', err);
  process.kill(process.ppid);
  process.reallyExit(1);
}) //监听未捕获的异常



program
  .command('upload')
  .description('upload a dir')
  .option('--uploadFrom <dir>', 'Root directory to upload files')
  .option('--uploadTo <dir>', 'Oss directory to put your uploaded files')
  .option('--env <env>', 'test or online or gray. for developer')
  .option('--config <configFilePath>', 'config file path, for detail: https://gitee.com/zhangbosss/ali-oss-upload')
  .action(function(argv) {
    console.log('项目执行路径: ', cwd);

    if (argv.env === 'test') { // 默认测试环境配置
      config = loadConfig(__dirname, '../upload-oss.test.json');
    }

    if (argv.env === 'gray') { // 默认测试环境配置
      config = loadConfig(__dirname, '../upload-oss.gray.json');
    }

    if (argv.config) { // 参数合并
      const configPath = path.resolve(cwd, argv.config);
      config = Object.assign(config, loadConfig(cwd, configPath), argv);
    }
    config = Object.assign(config, argv);

    if (!config.uploadFrom || !config.uploadTo) { // 入参校验
      throw Error('【uploadFrom】【uploadTo】 为必传参数');
    }
    // 禁止上传的文件名检验
    if (forbiddenUploadTo.indexOf(config.uploadTo) > -1) {
      throw Error('禁止使用dist、output、test、target、src...此类目录作为根路径, 避免命名冲突!!!');
    }


    new UploadOss({
      uploadFrom: config.uploadFrom,
      uploadTo: config.uploadTo,
      bucket: config.bucket,
      limit: config.limit,
      chunkSize: config.chunkSize,
      accessKeyId: config.accessKeyId,
      accessKeySecret: config.accessKeySecret,
      success() {
        console.log('================全部文件上传完毕================');
      },
      fail(err) {
        console.log('================文件上传失败================', err);
        // console.log('================若为测试环境或内网测试机器, 请检查是否绑定测试环境hosts: 120.52.32.211 upload.xueersi.com');
        process.reallyExit(1);
      }
    }).upload();
  })

program
  .command('uploadFile')
  .description('upload a single file')
  .option('--file <filePath>', 'File to upload')
  .option('--filename <fileName>', 'rename file')
  .option('--env <env>', 'test or online or gray. for developer')
  .option('--uploadTo <dir>', 'Oss directory to put your uploaded files')
  .option('--config <configFilePath>', 'config file path, for detail: https://gitee.com/zhangbosss/ali-oss-upload')
  .action(function(argv) {
    console.log('项目执行路径: ', cwd);
    if (!argv.file || !argv.uploadTo) { // 入参校验
      throw Error('【file】【uploadTo】 为必传参数');
    }
    // 禁止上传的文件名检验
    if (forbiddenUploadTo.indexOf(argv.uploadTo) > -1) {
      throw Error('禁止使用dist、output、test、target、src...此类目录作为根路径, 避免命名冲突!!!');
    }

    if (argv.env === 'test') { // 默认测试环境配置
      config = loadConfig(__dirname, '../upload-oss.test.json');
    }
    
    if (argv.env === 'gray') { // 默认测试环境配置
      config = loadConfig(__dirname, '../upload-oss.gray.json');
    }

    if (argv.config) { // 参数合并
      const configPath = path.resolve(cwd, argv.config);
      config = Object.assign(config, loadConfig(cwd, configPath));
    }
    config = Object.assign(config, argv);

    new UploadOss({
      uploadFrom: config.uploadFrom,
      uploadTo: config.uploadTo || config.uploadFrom,
      bucket: config.bucket,
      filename: config.filename,
      limit: config.limit,
      chunkSize: config.chunkSize,
      accessKeyId: config.accessKeyId,
      accessKeySecret: config.accessKeySecret,
      success() {
        console.log('================全部文件上传完毕================');
      },
      fail(err) {
        console.log('================文件上传失败================', err);
        // console.log('================若为测试环境, 请检查是否绑定测试环境hosts: 120.52.32.211 upload.xueersi.com');
        process.reallyExit(1);
      }
    }).uploadFile(path.resolve(cwd, argv.file));
  })

program.parse();

function loadConfig(cwd, configPath) {
  let jsonFilePath = path.resolve(cwd, configPath);
  let jsonConfig = {};
  try {
    jsonConfig = fs.readJSONSync(jsonFilePath);
  } catch (error) {
    console.error(jsonFilePath, "not found");
    throw new Error(error);
  }
  return jsonConfig;
}